package cool.xiaokang.familyaccount.controller;

import java.util.List;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.alibaba.fastjson.serializer.PropertyFilter;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

import cool.xiaokang.familyaccount.pojo.Region;
import cool.xiaokang.familyaccount.service.RegionService;
import cool.xiaokang.familyaccount.utils.ResponseUtils;
import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
@Controller
@Scope("prototype")
public class RegionAction extends ActionSupport implements ModelDriven<Region> {
	private static final long serialVersionUID = -3260675995731732588L;
	private Region region = new Region();
	private String region_ids;

	@Autowired
	private RegionService regionService;

	public String list() {
		List<Region> regions = regionService.findAll();
		ActionContext.getContext().put("list", regions);
		return "list";
	}

	public String listAjax() throws Exception {
		List<Region> regions = regionService.findAll();
		PropertyFilter filter = new PropertyFilter() {
			@Override
			public boolean apply(Object object, String name, Object value) {
				boolean flag = true;
				if (name.equals("topics")) {
					flag = false;
				}
				return flag;
			}
		};
		ResponseUtils.respList(ServletActionContext.getResponse(), regions, filter);
		return NONE;
	}

	@RequiresPermissions("region-add")
	public String add() {
		regionService.save(region);
		return "show";
	}

	@RequiresPermissions("region-edit")
	public String update() {
		regionService.update(region);
		return "show";
	}

	@RequiresPermissions("region-delete")
	public String delete() {
		// 批量删除
		String[] regionIds = region_ids.split(",");
		for (String region_id : regionIds) {
			regionService.delete(region_id);
		}
		return "show";
	}

	@Override
	public Region getModel() {
		return region;
	}
}
